#include "stdafx.h"
#include "mysql.h"


mysql::mysql()
{
}


mysql::~mysql()
{
}


mysql::conn_t mysql::connect(const std::string& url, const std::string& user, const std::string& password)
{
	try
	{
		driver_ptr_ = std::shared_ptr<sql::Driver>(get_driver_instance());
		conn_ptr_= std::shared_ptr<sql::Connection>(driver_ptr_->connect(url, user, password));
		conn_ptr_->setClientOption("characterSetResults", "utf8");

		connect_state_ = true;
	}
	catch(.../*sql::SQLException &e*/)
	{
		//
		connect_state_ = false;
	}

	return conn_ptr_;
}

bool mysql::is_connect()
{
	return connect_state_;
}

int mysql::excute_sql(const std::string& sql)
{
	if (!stat_ptr_.get())
		stat_ptr_ = std::shared_ptr<sql::Statement>(conn_ptr_->createStatement());

	save_point_ptr_ = std::shared_ptr<sql::Savepoint>(conn_ptr_->setSavepoint());

	return stat_ptr_->executeUpdate(sql);
}

template<class Value, class ...Args>
int mysql::excute_sql(const std::string& sql, Value value, Args... param)
{
	pre_stat_ptr_ = conn_ptr_->prepareStatement(sql);
	int size = 0;

	excute_sql(size, param...);

	return pre_stat_ptr_->executeUpdate();
}

mysql::result_t mysql::select_sql(const std::string& sql)
{
	if (!stat_ptr_.get())
		stat_ptr_ = std::shared_ptr<sql::Statement>(conn_ptr_->createStatement());

	return mysql::result_t(stat_ptr_->executeQuery(sql));
}

template<class Value, class ...Args>
mysql::result_t mysql::select_sql(const std::string& sql, Value value, Args... param)
{
	pre_stat_ptr_ = conn_ptr_->prepareStatement(sql);
	int size = 0;

	excute_sql(size, param...);

	return pre_stat_ptr_->executeQuery();
}

template<class Value>
int mysql::excute_sql( int index, Value value)
{
	index += 1;
	return state_exc(index, value);
}

void mysql::roll_back()
{
	if (!save_point_ptr_.get())
		return;

	conn_ptr_->rollback();

	conn_ptr_->commit();
}